package com.hotel.controller;

import com.hotel.dao.HomeMapper;
import com.hotel.pojo.Check;
import com.hotel.pojo.Home;
import com.hotel.service.CheckService;
import com.hotel.service.HomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/out")
public class OutController {
    @Autowired
    private  CheckService checkService;
    @Autowired
    private HomeMapper homeService;
    @RequestMapping("/list")
    public ModelAndView list(){
        ModelAndView mv = new ModelAndView();
        List<Check> checkList=checkService.queryAll();
        List<Check> collected = checkList.stream()
                .map(check -> {
                    int i = Integer.parseInt(check.getRoomId());
                    Home home = homeService.queryHomeById(i);
                    LocalDate checkOutTime = getLocalDate(check.getCheckOutTime());
                    LocalDate checkInTime = getLocalDate(check.getCheckInTime());
                    long daysBetween = ChronoUnit.DAYS.between(checkOutTime, checkInTime);
                    long day = daysBetween < 1L ? 1L : daysBetween;
                    check.setRoomNumber(home.getNum());
                    check.setPrice(home.getPrice());
                    check.setCount(String.valueOf(Math.abs(day)* (Long.parseLong(home.getPrice()))));
                    return check;
                }).collect(Collectors.toList());
        mv.addObject("checkList",collected);
        mv.setViewName("tui_list");
        return mv;
    }

    LocalDate getLocalDate(Date date){
        // 将Date转换为Instant，Instant表示一个时间点
        Instant instant = date.toInstant();

        // 由于LocalDate不包含时区信息，你需要指定一个时区来将Instant转换为LocalDate
        // 这里我们使用系统默认时区作为示例，但你也可以使用其他时区，比如ZoneId.of("UTC")
        ZoneId zoneId = TimeZone.getDefault().toZoneId();

        // 另一种方法是直接使用ZonedDateTime，它包含了时区信息
        ZonedDateTime zonedDateTime = instant.atZone(zoneId);

        // 最后，从ZonedDateTime中提取LocalDate
        LocalDate localDate = zonedDateTime.toLocalDate();
        return localDate;
    }


}
